package cn.v2tila.rsosa.management.service.serviceImpl;

import cn.v2tila.rsosa.management.entity.StudentEntity;
import cn.v2tila.rsosa.management.jpa.StudentJPA;
import cn.v2tila.rsosa.management.service.StudentService;
import cn.v2tila.rsosa.management.utils.PageDataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author v2tila on 15:52 2019/4/17
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentJPA studentJPA;
    @Override
    public PageDataResult getStu(int page, int limit, StudentEntity studentEntity) {
        PageDataResult pageDataResult = new PageDataResult();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        ExampleMatcher matcher;

        if(studentEntity.getId()==0){
            matcher = ExampleMatcher.matching()
                    .withMatcher("uniqueId", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id");
        }else{
            matcher = ExampleMatcher.matching();
        }
        Example<StudentEntity> example = Example.of(studentEntity,matcher);
        Page<StudentEntity> pages = studentJPA.findAll(example,pageable);
        List<StudentEntity> stuEntityList = pages.getContent();
        int count = studentJPA.findAll(example).size();
        pageDataResult.setData(stuEntityList);
        pageDataResult.setCount(count);
        return pageDataResult;
    }

    @Override
    public StudentEntity saveAndFlush(StudentEntity studentEntity) {
        return studentJPA.saveAndFlush(studentEntity);
    }

    @Override
    public StudentEntity findById(Integer id) {
            Optional<StudentEntity> findResult = studentJPA.findById(id);
            return findResult.get();
    }

    @Override
    public void deleteById(Integer id) {
        studentJPA.deleteById(id);
    }

    @Override
    public StudentEntity findByUniqueId(String uniqueId) {
        return studentJPA.findByUniqueId(uniqueId);
    }

}
